import store from '@/store'
import router from '@/router'

export function uniqueId() {
	return 'xxxxxxxx4xxxyxxx'.replace(/[xy]/g, c => {
		return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
	})
}
/**
 * 权限
 * @param {*} key
 */
export function hasPermission(key) {
	return window.SITE_CONFIG['permissions'].indexOf(key) !== -1 || false
}

/**
 * 清除登录信息
 */
export function clearLoginInfo() {
	sessionStorage.removeItem('token')
	store.commit('resetStore')
	router.options.isAddDynamicMenuRoutes = false
}
/**
 * 获取登录信息
 */
export function getLoginInfo() {
	return sessionStorage.getItem('token')
}
/**
 * 设置登录信息
 */
export function setLoginInfo(token) {
	return sessionStorage.setItem('token', token)
}

/**
 * 获取uuid
 */
export function getUUID() {
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
		return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
	})
}

/**
 * 树形数据转换
 * @param {*} data
 * @param {*} id
 * @param {*} pid
 */
export function treeDataTranslate(data, id = 'id', pid = 'pid') {
	var res = []
	var temp = {}
	for (var i = 0; i < data.length; i++) {
		temp[data[i][id]] = data[i]
	}
	for (var k = 0; k < data.length; k++) {
		if (!temp[data[k][pid]] || data[k][id] === data[k][pid]) {
			res.push(data[k])
			continue
		}
		if (!temp[data[k][pid]]['children']) {
			temp[data[k][pid]]['children'] = []
		}
		temp[data[k][pid]]['children'].push(data[k])
		data[k]['_level'] = (temp[data[k][pid]]._level || 0) + 1
	}
	return res
}

// 递归
// 1. 结束条件 treeData为空，返回[]
// 2. 结束条件 treeData不为空 返回[当前元素].concat(transfer(子元素))
// 需要实现transfer函数, 输入树形结构, 输出结果为一个一维数组:arrayData
export function transferData(treeData) {
	const data = JSON.parse(JSON.stringify(treeData)),
		res = [];
	const dfs = (tree) => {
		tree.forEach((item) => {
			if (item.list) {
				dfs(item.list);
				delete item.list;
			}
			res.push(item);
		});
	};
	dfs(data);
	return res;
}
export function setTheme(color) {
	// document.documentElement 是全局变量时
	const el = document.documentElement
	// const el = document.getElementById('xxx')
	console.log(color, '主题颜色')
	// 获取 css 变量
	getComputedStyle(el).getPropertyValue(`--el-color-primary`)

	// 设置 css 变量
	el.style.setProperty('--el-color-primary', color)
}

export function clearUrlParam(_this, event) {
	let urlParam = _this.serialize()
	let splitStr = urlParam.split('&')
	var newStr = ''
	var label = ''
	for (var i = 0; i < splitStr.length; i++) {
		let splitStrArray = splitStr[i].split('=')
		if (splitStrArray[1].length > 0) {
			newStr += unescape(splitStrArray[0] + '=' + splitStrArray[1] + '&')
		}
	}
	if (newStr != '') {
		label = '?'
		newStr = newStr.substring(0, newStr.length - 1)
	}
	event.preventDefault()
	return _this.attr('action') + label + newStr
}

// 进入全屏
export function launchFullscreen(element) {
	element = element || document.documentElement
	if (element.requestFullscreen) {
		element.requestFullscreen();
	} else if (element.mozRequestFullScreen) {
		//不同浏览器之间需要添加前缀
		element.mozRequestFullScreen();
	} else if (element.msRequestFullscreen) {
		element.msRequestFullscreen();
	} else if (element.webkitRequestFullscreen) {
		element.webkitRequestFullScreen();
	}
}

// 退出全屏
export function exitFullscreen() {
	if (document.exitFullscreen) {
		document.exitFullscreen();
	} else if (document.msExitFullscreen) {
		document.msExitFullscreen();
	} else if (document.mozCancelFullScreen) {
		document.mozCancelFullScreen();
	} else if (document.webkitExitFullscreen) {
		document.webkitExitFullscreen();
	}
}

/* eslint-disable no-nested-ternary */
/* eslint-disable no-restricted-syntax */
/* eslint-disable guard-for-in */
/**
 * num 小于0，左缩进num*2个空格； 大于0，右缩进num*2个空格。
 * @param {string} str 代码
 * @param {number} num 缩进次数
 * @param {number} len 【可选】缩进单位，空格数
 */
export function indent(str, num, len = 2) {
	if (num === 0) return str
	const isLeft = num < 0;
	const result = [];
	let reg;
	let
		spaces = ''
	if (isLeft) {
		num *= -1
		reg = new RegExp(`(^\\s{0,${num * len}})`, 'g')
	} else {
		for (let i = 0; i < num * len; i++) spaces += ' '
	}

	str.split('\n').forEach(line => {
		line = isLeft ? line.replace(reg, '') : spaces + line
		result.push(line)
	})
	return result.join('\n')
}

// 首字母大小
export function titleCase(str) {
	return str.replace(/( |^)[a-z]/g, L => L.toUpperCase())
}

// 下划转驼峰
export function camelCase(str) {
	return str.replace(/-[a-z]/g, str1 => str1.substr(-1).toUpperCase())
}

export function isNumberStr(str) {
	return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str)
}

export const exportDefault = 'export default '

export const beautifierConf = {
	html: {
		indent_size: '2',
		indent_char: ' ',
		max_preserve_newlines: '-1',
		preserve_newlines: false,
		keep_array_indentation: false,
		break_chained_methods: false,
		indent_scripts: 'separate',
		brace_style: 'end-expand',
		space_before_conditional: true,
		unescape_strings: false,
		jslint_happy: false,
		end_with_newline: true,
		wrap_line_length: '110',
		indent_inner_html: true,
		comma_first: false,
		e4x: true,
		indent_empty_lines: true
	},
	js: {
		indent_size: '2',
		indent_char: ' ',
		max_preserve_newlines: '-1',
		preserve_newlines: false,
		keep_array_indentation: false,
		break_chained_methods: false,
		indent_scripts: 'normal',
		brace_style: 'end-expand',
		space_before_conditional: true,
		unescape_strings: false,
		jslint_happy: true,
		end_with_newline: true,
		wrap_line_length: '110',
		indent_inner_html: true,
		comma_first: false,
		e4x: true,
		indent_empty_lines: true
	}
}

function stringify(obj) {
	return JSON.stringify(obj, (key, val) => {
		if (typeof val === 'function') {
			return `${val}`
		}
		return val
	})
}

function parse(str) {
	JSON.parse(str, (k, v) => {
		if (v.indexOf && v.indexOf('function') > -1) {
			return eval(`(${v})`)
		}
		return v
	})
}

export function jsonClone(obj) {
	return parse(stringify(obj))
}

// 深拷贝对象
export function deepClone(obj) {
	const _toString = Object.prototype.toString

	// null, undefined, non-object, function
	if (!obj || typeof obj !== 'object') {
		return obj
	}

	// DOM Node
	if (obj.nodeType && 'cloneNode' in obj) {
		return obj.cloneNode(true)
	}

	// Date
	if (_toString.call(obj) === '[object Date]') {
		return new Date(obj.getTime())
	}

	// RegExp
	if (_toString.call(obj) === '[object RegExp]') {
		const flags = []
		if (obj.global) {
			flags.push('g')
		}
		if (obj.multiline) {
			flags.push('m')
		}
		if (obj.ignoreCase) {
			flags.push('i')
		}

		return new RegExp(obj.source, flags.join(''))
	}

	const result = Array.isArray(obj) ? [] : obj.constructor ? new obj.constructor() : {}

	for (const key in obj) {
		result[key] = deepClone(obj[key])
	}

	return result
}

const toStr = Function.prototype.call.bind(Object.prototype.toString)
export function isObjectObject(t) {
	return toStr(t) === '[object Object]'
}
export function isObjectArray(t) {
	return toStr(t) === '[object Array]'
}
export function isObjectNull(t) {
	return toStr(t) === '[object Null]'
}
export function isObjectUnde(t) {
	return toStr(t) === '[object Undefined]'
}



/**
 * 日期类型格式化方法
 * @param fmt 需要格式化成的格式
 * @returns {*|string}
 */
Date.prototype.format = function(fmt) {

	fmt = fmt || "yyyy-MM-dd";
	let o = {
		"M+": this.getMonth() + 1, //月份
		"d+": this.getDate(), //日
		"h+": this.getHours(), //小时
		"m+": this.getMinutes(), //分
		"s+": this.getSeconds(), //秒
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度
		"S": this.getMilliseconds() //毫秒
	};

	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	}

	for (const k in o) {
		if (new RegExp("(" + k + ")").test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k])
				.length)));
		}
	}

	return fmt;
};